package com.glandroid.qvod;

import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private AudioManager mAudioManager;
    private ProgressBar pb;
    private SurfaceView sv;
    private SeekBar seekBar1;
    private SharedPreferences sp;
    private MediaPlayer mediaPlayer;
    private Timer timer;
    private RelativeLayout rl_topbar;
    private TimerTask task;
    private RelativeLayout rl;
    private LinearLayout ll_bottom;
    private ImageView iv;
    private TextView tv_pro,tv_max;
    private TextView tvSound,tvBright;
    private Utils utils;
    private ImageView iv_extend;
    private Handler handler;
    private float downX, downY;
    private int FACTOR = 50;
    private float screen_widthPixels,screen_heightPixels;
    private int AUDIE_NOW_PROGREE = 0;//当前播放进度
    private final int HANDLE_SEND_PROGREE = 1;
    private float mBrightness = 0;//当前亮度
    public MainActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        sv.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                System.out.println("SurfaceView被创建了");
                try {
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setDataSource("http://queswoo.com/xyjy.mp4");

                    // 播放视频必须设置播放的容器，通过sv得到他的holder
                    mediaPlayer.setDisplay(sv.getHolder());
                    mediaPlayer.prepareAsync();// 异步的准备，开启子线程


                    mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                        @Override
                        public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                            setVideoParams(mediaPlayer,false);
//                            changeVideoSize();
                        }
                    });
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putInt("position", 0);
                            editor.commit();
                        }
                    });
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            pb.setVisibility(View.INVISIBLE);
                            mediaPlayer.start();
                            int position = sp.getInt("position", 0);
                            mediaPlayer.seekTo(position);
                            tv_max.setText(utils.stringForTime(mediaPlayer.getDuration()));
                            timer = new Timer();
                            task = new TimerTask() {
                                @Override
                                public void run() {
                                    int max = mediaPlayer.getDuration();
                                    AUDIE_NOW_PROGREE = mediaPlayer.getCurrentPosition();
                                    //Log.i("imooc","总：" + max + "，当前："+progress + "，时间："+utils.stringForTime(progress));
                                    seekBar1.setMax(max);
                                    seekBar1.setProgress(AUDIE_NOW_PROGREE);
                                    Message message = new Message();
                                    message.what = HANDLE_SEND_PROGREE;
                                    mHandler.sendMessage(message);
                                }
                            };
                            timer.schedule(task, 0, 500);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                System.out.println("SurfaceView被销毁了");
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    int position = mediaPlayer.getCurrentPosition();
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("position", position);
                    editor.commit();
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                    timer.cancel();
                    task.cancel();
                    timer = null;
                    task = null;
                }
            }
        });


        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });
        sv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getX();
                        downY = event.getY();
                        ll_bottom.setVisibility(View.VISIBLE);
                        if(mediaPlayer.isPlaying()){
                            iv.setVisibility(View.VISIBLE);
                            iv.setImageDrawable( getResources().getDrawable(R.drawable.ic_pause) );
                        }else if (mediaPlayer != null && !mediaPlayer.isPlaying()){
                            iv.setVisibility(View.VISIBLE);
                            iv.setImageDrawable( getResources().getDrawable(R.drawable.ic_play) );
                        }
                        new Thread(){
                            @Override
                            public void run() {
                                SystemClock.sleep(3000);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ll_bottom.setVisibility(View.INVISIBLE);
                                        iv.setVisibility(View.GONE);
                                    }
                                });
                            }
                        }.start();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        float distanceX = event.getX() - downX;
                        float distanceY = event.getY() - downY;
                        if (downX > screen_widthPixels - screen_widthPixels/3 && Math.abs(distanceX) < 50 && (distanceY > FACTOR||distanceY<-FACTOR)) {
                            // TODO 调节音量
                            setVolume(-distanceY);
                        }
                        if (downX < screen_widthPixels/3 && Math.abs(distanceX) < 50 && (distanceY > FACTOR||distanceY<-FACTOR)) {
                            // TODO 调节亮度
                            setBrightness(-distanceY);
                        }
                        if (Math.abs(distanceY) < 200 && (distanceX > FACTOR||distanceX<-FACTOR)) {
                            // TODO 播放进度调节
                            int currentT = mediaPlayer.getCurrentPosition();
                            //播放的位置
                            mediaPlayer.seekTo(currentT + (distanceX > FACTOR?5000:-5000));
                            downX = event.getX();
                            downY = event.getY();
                            Log.i("info", "distanceX快进=" + distanceX);
                        }
                        break;
                }
                return true;
            }
        });
        iv.setOnClickListener(this);
        iv_extend.setOnClickListener(this);
    }

    private void setBrightness(float detlaY) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        mBrightness= attributes.screenBrightness;
        float index= detlaY/screen_heightPixels/3;
        mBrightness+=index;
        if (mBrightness>1.0f){
            mBrightness=1.0f;
        }
        if (mBrightness<0.01f){
            mBrightness=0.01f;
        }
        attributes.screenBrightness=mBrightness;
        getWindow().setAttributes(attributes);
        tvBright.setVisibility(View.VISIBLE);
        tvBright.setText("亮度:" + mBrightness);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvBright.setVisibility(View.GONE);
            }
        },1000);
    }


    private void initData() {
        utils = new Utils();
        mAudioManager= (AudioManager) getSystemService(AUDIO_SERVICE);
        try {
            mBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        sp = getSharedPreferences("config", MODE_PRIVATE);
        Display display = getWindowManager().getDefaultDisplay();
        screen_heightPixels = display.getHeight();
        screen_widthPixels = display.getWidth();
        setRelativeParams(screen_widthPixels,screen_widthPixels* 9f / 16f,false);
        handler = new Handler();
//        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width,width*9/16);
//        rl.setLayoutParams(layoutParams);

//        float bright_max = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
//        float bright_min = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
//        Log.i("imooc",bright_max + "");
//        Log.i("imooc",bright_min + "");
//        //初始化音频管理器
//        AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//        //获取系统最大音量
//        int maxVolume=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//        Log.i("imooc",maxVolume + "");
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
        iv_extend = (ImageView) findViewById(R.id.iv_extend);
        rl_topbar = (RelativeLayout) findViewById(R.id.rl_topbar);
        pb = (ProgressBar) findViewById(R.id.pb);
        sv = (SurfaceView) findViewById(R.id.sv);
        rl = (RelativeLayout) findViewById(R.id.rl);
        iv = (ImageView) findViewById(R.id.iv_center);
        ll_bottom = (LinearLayout) findViewById(R.id.ll_bottom);
        tv_pro = (TextView) findViewById(R.id.tv_pro);
        tv_max = (TextView) findViewById(R.id.tv_max);
        tvSound = (TextView) findViewById(R.id.tv_sound);
        tvBright = (TextView) findViewById(R.id.tv_bright);
    }


    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HANDLE_SEND_PROGREE:
                    tv_pro.setText(utils.stringForTime(AUDIE_NOW_PROGREE));
                    break;
            }
        }
    };


    private void setVolume(float detlaY) {
        int max=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current=mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.i("imooc",max+"___");
        int index=(int)(detlaY/screen_widthPixels*max);
        int curretnV=Math.max(current+index,0);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,curretnV>max?max:curretnV,0);
        tvSound.setVisibility(View.VISIBLE);
        tvSound.setText("音量:" + curretnV);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvSound.setVisibility(View.GONE);
            }
        },1000);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //变成横屏了
            rl_topbar.setVisibility(View.GONE);
            setVideoParams(mediaPlayer, true);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            rl_topbar.setVisibility(View.VISIBLE);
            //变成竖屏了
            setVideoParams(mediaPlayer, false);
        }
    }

    /**
     * 设置SurfaceView的参数
     *
     * @param mediaPlayer
     * @param isLand
     */
    public void setVideoParams(MediaPlayer mediaPlayer, boolean isLand) {
        //获取SurfaceView的参数
        ViewGroup.LayoutParams sv_paramters = sv.getLayoutParams();
        //设置宽高比为16/9
        screen_widthPixels = getResources().getDisplayMetrics().widthPixels;
        screen_heightPixels = getResources().getDisplayMetrics().widthPixels * 9f / 16f;
        //取消全屏
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (isLand) {
            screen_heightPixels = getResources().getDisplayMetrics().heightPixels;
            //设置全屏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        //设置relativelayout的宽高，为了防止mediaplayer未初始化成功就调用，因此relativelayout单独用一个方法设置宽高
        setRelativeParams(screen_widthPixels,screen_heightPixels,isLand);
        //获取MediaPlayer的宽高
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();
Log.i("imooc",videoHeight + "___________");
        float video_por = videoWidth / videoHeight;
        float screen_por = screen_widthPixels / screen_heightPixels;
        //16:9    16:12
        if (screen_por > video_por) {
            sv_paramters.height = (int) screen_heightPixels;
            sv_paramters.width = (int) (screen_heightPixels * screen_por);
        } else {
            //16:9  19:9
            sv_paramters.width = (int) screen_widthPixels;
            sv_paramters.height = (int) (screen_widthPixels / screen_por);
        }
        sv.setLayoutParams(sv_paramters);
    }
    /**
     * 设置外层relativelayout的参数
     *
     * @param isLand
     */
    public void setRelativeParams(float screen_widthPixels,float screen_heightPixels,boolean isLand) {
        //获取surfaceView父布局的参数
        ViewGroup.LayoutParams rl_paramters = rl.getLayoutParams();
        rl_paramters.width = (int) screen_widthPixels;
        rl_paramters.height = (int) screen_heightPixels;
        rl.setLayoutParams(rl_paramters);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_center:
                if (mediaPlayer.isPlaying()){
                    new Thread(){
                        @Override
                        public void run() {
                            iv.setImageDrawable( getResources().getDrawable(R.drawable.ic_play) );
                            ll_bottom.setVisibility(View.VISIBLE);
                            mediaPlayer.pause();
                            SystemClock.sleep(3000);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ll_bottom.setVisibility(View.INVISIBLE);
                                    iv.setVisibility(View.GONE);
                                }
                            });
                        }
                    }.start();
                }else if(mediaPlayer != null && !mediaPlayer.isPlaying()){
                    new Thread(){
                        @Override
                        public void run() {
                            iv.setImageDrawable( getResources().getDrawable(R.drawable.ic_pause) );
                            ll_bottom.setVisibility(View.VISIBLE);
                            mediaPlayer.start();
                            SystemClock.sleep(3000);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ll_bottom.setVisibility(View.INVISIBLE);
                                }
                            });
                        }
                    }.start();
                }
                break;
            case R.id.iv_extend:
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //变成竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //变成横屏了
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //变成竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else{
            super.onBackPressed();
        }
    }
}
